import * as Cesium from 'cesium';
import gsap from 'gsap';

export default class RadarMaterialProperty {
  constructor(name) {
    this.name = name;

    this.definitionChanged = new Cesium.Event();
    Cesium.Material._materialCache.addMaterial('RadarMaterial', {
      fabric: {
        type: 'RadarMaterial',
        uniforms: {
          uTime: 0,
          image: Cesium.Material.DefaultImageId,
        },
        source: `
          // 声明全局的纹理采样器
          uniform sampler2D image; 
          czm_material czm_getMaterial(czm_materialInput materialInput) {
            // 获取默认材质
            czm_material material = czm_getDefaultMaterial(materialInput);

            // 旋转 uv
            vec2 center = vec2(0.5);
            vec2 offset = materialInput.st - center;
            vec2 rotatedOffset = mat2(
              cos(uTime), -sin(uTime),
              sin(uTime), cos(uTime)
            ) * offset;
            vec2 newSt = rotatedOffset + center;

            // 将旋转后的 newSt 转换为 vec2 类型进行距离计算
            vec2 st2d = newSt;

            //设置圆 外部透明 内部不透明
            float alpha = 1.0 - step(0.5, distance(st2d,vec2(0.5)));

            //按照角度来设置强弱
            float angle = atan(st2d.y-0.5,st2d.x-0.5);
            //angle是从-pi到pi的,所以如果要设置从0-1的转变,需要加上pi
            float strength = (angle+3.1416)/6.2832;

            //将强弱与透明度结合
            alpha = alpha*strength;

            material.alpha = alpha;
            material.diffuse = vec3(newSt.x,newSt.y,1.0); 
     
            return material;
          }
        `,
      },
    });

    this.params = {
      uTime: 0,
      image: Cesium.Material.DefaultImageId,
    };
    gsap.to(this.params, {
      uTime: 2 * 3.14159, // 让 uTime 覆盖一个完整的圆周
      duration: 4,
      repeat: -1,
      //线性
      ease: 'linear',
      //来回
      // yoyo: true,
    });
  }
  getType() {
    // 返回材质类型
    return 'RadarMaterial';
  }
  getValue(time, result) {
    result.uTime = this.params.uTime;
    result.image = this.params.image; // 传递 image 这个 uniform
    return result;
  }
  equals(other) {
    // 判断两个材质是否相等
    return other instanceof RadarMaterialProperty && this.name === other.name;
  }
}
